0503. 下一个更大元素 II【中等】
1. 📝 题目描述
给定一个循环数组 nums ( nums[nums.length - 1] 的下一个元素是 nums[0] ),返回 nums 中每个元素的 下一个更大元素。
数字 x 的 下一个更大的元素 是按数组遍历顺序,这个数字之后的第一个比它更大的数,这意味着你应该循环地搜索它的下一个更大的数。如果不存在,则输出 -1。
示例 1:
txt
输入: nums = [1,2,1]
输出: [2,-1,2]
解释: 第一个 1 的下一个更大的数是 2;
数字 2 找不到下一个更大的数;
第二个 1 的下一个最大的数需要循环搜索,结果也是 2。1
2
3
4
5
2
3
4
5
示例 2:
txt
输入: nums = [1,2,3,4,3]
输出: [2,3,4,-1,4]1
2
2
提示:
1 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9
2. 🎯 s.1 - 单调栈
c
int* nextGreaterElements(int* nums, int numsSize, int* returnSize) {
*returnSize = numsSize;
int* res = (int*)malloc(sizeof(int) * numsSize);
int* stack = (int*)malloc(sizeof(int) * numsSize);
int top = 0;
for (int i = 0; i < numsSize; i++) res[i] = -1;
for (int i = 0; i < 2 * numsSize; i++) {
while (top > 0 && nums[stack[top - 1]] < nums[i % numsSize])
res[stack[--top]] = nums[i % numsSize];
if (i < numsSize) stack[top++] = i;
}
free(stack);
return res;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
js
/**
* @param {number[]} nums
* @return {number[]}
*/
var nextGreaterElements = function (nums) {
const n = nums.length
const res = new Array(n).fill(-1)
const stack = []
for (let i = 0; i < 2 * n; i++) {
while (stack.length && nums[stack[stack.length - 1]] < nums[i % n]) {
res[stack.pop()] = nums[i % n]
}
if (i < n) stack.push(i)
}
return res
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
py
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
n = len(nums)
res = [-1] * n
stack = []
for i in range(2 * n):
while stack and nums[stack[-1]] < nums[i % n]:
res[stack.pop()] = nums[i % n]
if i < n:
stack.append(i)
return res1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
- 时间复杂度:
- 空间复杂度:
算法思路:
- 将数组视为循环数组,遍历两倍长度
- 维护单调递减栈,栈中存储下标
- 当当前元素大于栈顶对应值时,弹出栈顶并记录结果